<?php

declare (strict_types = 1);

namespace app\controller\v1;

use app\model\ProductLike;
use app\service\ProductService;
use think\Request;
use app\service\ProductsService;
class ProductController extends BaseAPIController
{
    // 收藏商品
    public function likeProduct(Request $request)
    {
        $goodsId = $this->request->get('goods_id');
        $userId = $this->userService->getCurrentUserId();
        // 判断是否收藏过
        $like = ProductLike::where('user_id', $userId)->where('product_id', $goodsId)->find();
        if ($like) {
            $like->delete();
            return $this->error('已取消收藏');
        }
        $res = ProductLike::create([
            'user_id' => $userId,
            'product_id' => $goodsId,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
        if (!$res) {
            return $this->error('收藏失败');
        }
        return $this->success([],'收藏成功');
    }

    // 获取产品详情
    public function getNormalProductDetail(Request $request)
    {
        $goodsId = $this->request->get('goods_id');
        try {
            $product = (new ProductService())->getNormalProductDetail($goodsId);
        } catch (\Exception $e) {
            return $this->error($e->getMessage().$e->getLine());
        }
        return $this->success($product);
    }


    // 生成小程序码
    public function getMiniQrcode(Request $request)
    {
        $goodsId = $this->request->get('goods_id');
        try {
            $product = (new ProductService())->getMiniQrcode($goodsId);
        } catch (\Exception $e) {
            return $this->error($e->getMessage().$e->getLine());
        }
        return $this->success($product);
    }

    // 获取热门推荐产品,todo暂时随机获取10个回来,后续根据产品点击量排序
    public function getHotRecommend()
    {
        $product = (new ProductsService())->getHotRecommend();
        return $this->success($product);
    }


     // 搜索产品
    public function getSearchProduct(Request $request)
    {
        $product = (new ProductsService())->getSearchProduct($request);
        return $this->success($product);
    }
}
